package com.oocl.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.pojo.User;
import com.oocl.service.UserService;
import com.oocl.service.impl.UserServiceImpl;
import com.oocl.util.DateUtil;

public class FindUsersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService userService = new UserServiceImpl();
 

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		System.out.println("tttt");
		List<User> users = userService.findAll();
		String usersTempPath = this.getServletContext().getRealPath("/temp/");
		File file = new File(usersTempPath);
		if(!file.exists()){
			file.mkdirs();
		}
		File[] files = file.listFiles();
		if(files.length>0){
			for (File f : files) {
				f.delete();
			}
		}
		
		response.setContentType("text/html;charset=utf-8");
		StringBuilder sb = new StringBuilder();
		sb.append("<table border='1'>");
		sb.append("<thead>");
		sb.append("<tr><th>ID</th><th>用户名</th><th>工资</th><th>生日</th><th>性别</th><th>头像</th></tr>");
		sb.append("</thead>");
		for(int i=0;i<users.size();i++){
			sb.append("<tr>");
			sb.append("<td>");
			sb.append(users.get(i).getId());
			sb.append("</td>");
			
			sb.append("<td>");
			sb.append(users.get(i).getUsername());
			sb.append("</td>");
			
			sb.append("<td>");
			sb.append(users.get(i).getSalary());
			sb.append("</td>");
			
			sb.append("<td>");
			sb.append(DateUtil.dateToStr(users.get(i).getBirthDate(), "yyyy-MM-dd"));
			sb.append("</td>");
			
			sb.append("<td>");
			if(users.get(i).isSex()){
				sb.append("男");
			}else {
				sb.append("女");
			}
			sb.append("</td>");
			if(users.get(i).getHeadImage().length>0){
				sb.append("<td><img src='http://localhost:8080/homework_7_24/temp"+File.separator+"00"+i+".jpg"+"' width=70 height=70></img>");
				OutputStream out = new FileOutputStream(usersTempPath+File.separator+"00"+i+".jpg");
				out.write(users.get(i).getHeadImage());
				out.flush();
				out.close();
				sb.append("</td>");
			}
			sb.append("</tr>");
		}
		sb.append("</table>");
		
		response.getWriter().write(sb.toString());
	}


}
